setwd('D:/Rassignment/RNAseq_Data')  # 使用正斜杠避免转义问题
library(tidyverse)
library(DESeq2)

# 1. 数据读取与预处理 ----
clin_inf <- read.csv("clin_inf.csv", header = TRUE)
count <- read.csv("count.csv", header = TRUE, check.names = FALSE)

# 样本名处理：一步完成所有重命名
colnames(count) <- colnames(count) %>%
  str_replace("\\.$", "") %>%          # 移除末尾点
  str_replace("^gene_i", "gene_id") %>% # 修正列名
  str_replace("^X(\\d)", "PTB\\1")     # X开头数字转为PTB格式

# 2. 数据整理 ----
# 基因ID设为行名，样本列转为整数
count_data <- count %>%
  column_to_rownames("gene_id") %>%
  mutate(across(everything(), round)) %>%  # 所有计数四舍五入
  as.matrix()

# 3. 临床信息处理 ----
clin_inf <- clin_inf %>%
  mutate(AgeGroup = ifelse(年龄 < 65, "Young", "Old") %>% 
           mutate(AgeGroup = factor(AgeGroup, levels = c("Young", "Old"))) %>%
           arrange(样本名称)  # 确保样本排序一致
         
         # 4. 样本顺序对齐 ----
         count_data <- count_data[, clin_inf$样本名称, drop = FALSE]
         
         # 5. DESeq2分析 ----
         dds <- DESeqDataSetFromMatrix(
           countData = count_data,
           colData = clin_inf,
           design = ~ AgeGroup
         )
         
         dds <- DESeq(dds, quiet = TRUE)  # 静默模式减少输出
         
         # 6. 结果提取 ----
         res <- results(dds, contrast = c("AgeGroup", "Old", "Young"), alpha = 0.05) %>%
           as.data.frame() %>%
           rownames_to_column("gene_id") %>%
           arrange(padj)
         
         # 7. 结果保存 ----
         write.csv(res, "DESeq2_AgeGroup_Results.csv", row.names = FALSE)
         
         # 可选：添加版本信息
         packageVersion("DESeq2")  # 记录使用的DESeq2版本